package com.yuyou.activity.group.service.lock;

import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.yuyou.activity.comm.service.tool.MailUtil;
import com.yuyou.activity.util.util.LogUtil;
import com.yuyou.activity.util.util.MessageUtil;
import com.yuyou.activity.util.util.SpringUtil;
@Service
public class MapLock {
	
    private static  final Logger logger = LoggerFactory.getLogger(MessageUtil.class);
	
	private final static long sleepTime=300;
	
	private final static int timelimit=200;
	
	public static final ConcurrentHashMap<String, String> lockCache = new ConcurrentHashMap<String, String>(64);
	
	public static boolean trylock(String key) throws InterruptedException {
		LogUtil.info(logger, "lockCache:"+lockCache.size());
		try{
			int tryTimes = timelimit;
			do{
				String isNull = lockCache.putIfAbsent(key,"lock");
				if (isNull != null) {
					//没有获取到锁
					tryTimes--;
					System.out.println("tryTimes:"+tryTimes);
					Thread.sleep(sleepTime);
				} else {
					//获取到锁
					return true;
				}
			}while (tryTimes > 0);
			return false;
		}catch(Exception e){
			LogUtil.error(logger, "deadLock-"+key+":",e);
			MailUtil mailUtil=(MailUtil)SpringUtil.getBean("mailUtil");
			removeLock(key);			
			mailUtil.sendEmail("lockError-", key);
			return false;
		}

	}
	
	public static void removeLock(String key) throws InterruptedException {
		if(lockCache.containsKey(key)){
			lockCache.remove(key);
		}	
	}
	
	
	public static void main(String[] args) throws InterruptedException {
		//需要注意的是，如果lock对象是自定义对象，那么要重写它的equals方法和hashCode方法；
		String lock = "testLock";
		new TestThread(lock,"1").start();
		new TestThread(lock,"2").start();
		new TestThread(lock,"3").start();
		new TestThread(lock,"4").start();
		new TestThread(lock,"5").start();
		new TestThread(lock,"6").start();
		new TestThread(lock,"7").start();
		new TestThread(lock,"8").start();
		new TestThread(lock,"9").start();
	}
	
	static class TestThread extends Thread{
		private String lock;
		
		private String name;
		
		TestThread(String lock,String name){
			this.lock = lock;
			this.name=name;
		}
		
		public void run() {
			try {
				boolean b=MapLock.trylock(lock);
				if(b){
					System.out.println("sdfsdfsdfsd"+":"+name);
				}
				MapLock.removeLock(lock);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
}

